# -*- coding: utf-8 -*-

import os

from flask import Flask
from werkzeug.utils import import_string

from mongoengine import connect

from webutils_wechat.redis.flask import FlaskRedisClient
from webutils_wechat.http_client.flask import FlaskHttpClient
from webutils_wechat.auth.flask import Auth
from webutils_wechat.wechat.flask import Wechat

from utils.logger import WebWechatLogger
from utils.common import BASE_PATH


logger = WebWechatLogger()
redis = FlaskRedisClient()

http_client = FlaskHttpClient()
wechat = Wechat()
auth = Auth()

db = None


def create_app(config_env=None):
    app = Flask(__name__)

    if config_env is None:
        config_env = 'WEB_CONF_REPO'
    filepath = os.environ.get(config_env, os.path.join(BASE_PATH, 'etc', 'dev'))
    filepath = os.path.abspath(filepath)
    if os.path.isdir(filepath):
        for dirpath, _, filenames in os.walk(filepath):
            for filename in filenames:
                filename = os.path.join(dirpath, filename)
                try:
                    app.config.from_pyfile(filename, silent=True)
                except:
                    pass
    else:
        app.config.from_pyfile(filepath)

    logger.init_app(app)
    global db
    app.mongodb = db = connect(
        app.config['MONGODB_DB'],
        host=app.config.get('MONGODB_URI', 'mongodb://localhost:27017'),
    )

    redis.init_app(app)

    http_client.init_app(app)
    wechat.init_app(app)
    auth.init_app(app)

    for bp in app.config.get('INSTALLED_BLUEPRINTS', []):
        bp = import_string(bp)
        app.register_blueprint(bp)

    return app
